<template>
  <div class="container">
    <div class="app-container">
      <div class="role-operator">
        <el-button size="mini" type="primary" @click="showDialog = true">添加角色</el-button>
      </div>
      <el-table v-loading="loading" :data="tableData" border :header-cell-style="{background:'#f5f6f8',color:'#909399'}">
        <el-table-column type="index" width="50" align="center" label="序号">
          <template v-slot="scope">
            {{ (pager.page - 1) * pager.pagesize + scope.$index + 1 }}
          </template>
        </el-table-column>
        <el-table-column prop="name" width="200" align="center" label="角色">
          <template v-slot="{row}">
            <el-input v-if="row.isEdit" v-model="row.editRow.name" size="mini" />
            <span v-else>
              {{ row.name }}
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="state" width="200" align="center" label="启用">
          <template v-slot="{row}">
            <el-switch
              v-if="row.isEdit"
              v-model="row.editRow.state"
              :active-value="1"
              :inactive-value="0"
            />
            <span v-else>{{ row.state === 1?'已启用':row.state === 0?'未启用':'无' }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="description" align="center" label="描述">
          <template v-slot="{row}">
            <el-input
              v-if="row.isEdit"
              v-model="row.editRow.description"
              type="textarea"
              :rows="2"
            />
            <span v-else>{{ row.description }}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="操作">
          <template v-slot="{row}">
            <div v-if="row.isEdit">
              <el-button size="mini" type="primary" @click="editRole(row)">提交</el-button>
              <el-button size="mini" @click="row.isEdit = false">取消</el-button>
            </div>
            <div v-else>
              <el-button type="text" size="small" @click="handlePermission(row.id)">分配权限</el-button>
              <el-button type="text" size="small" @click="handleEdit(row)">编辑</el-button>
              <el-popconfirm
                title="确定删除该角色吗？"
                style="margin-left: 10px;"
                @onConfirm="handleDel(row.id)"
              >
                <el-button slot="reference" type="text" size="small">删除</el-button>
              </el-popconfirm>
            </div>
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination">
        <el-pagination
          :page-size="5"
          :pager-count="7"
          layout=" prev, pager, next"
          :total="total"
          :current-page="pager.page"
          @current-change="pageChange"
          @prev-click="pagePrev"
          @next-click="pageNext"
        />
      </div>
    </div>
    <!-- 新增角色 -->
    <el-dialog
      title="新增角色"
      :visible.sync="showDialog"
      width="30%"
      @close="close"
    >
      <el-form ref="form" :model="roleForm" label-width="120px" :rules="rules">
        <el-form-item label="角色名称" prop="name">
          <el-input id="name" v-model="roleForm.name" style="width: 80%" size="small" />
        </el-form-item>
        <el-form-item label="启用" prop="state">
          <el-switch
            v-model="roleForm.state"
            :active-value="1"
            :inactive-value="0"
          />
        </el-form-item>
        <el-form-item label="角色描述" prop="description">
          <el-input
            id="introduce"
            v-model="roleForm.description"
            style="width: 80%"
            type="textarea"
            :rows="4"
          />
        </el-form-item>
        <el-form-item>
          <el-row type="flex" justify="center">
            <el-col :span="12">
              <el-button size="mini" type="primary" @click="addRole">提交</el-button>
              <el-button size="mini" @click="close">取消</el-button>
            </el-col>
          </el-row>
        </el-form-item>
      </el-form>
    </el-dialog>
    <SetPermission ref="setPermission" />
  </div>
</template>
<script>
import { getRolesList, delRole, addRole, editRole } from '@/api/role'
import SetPermission from './components/SetPermission.vue'
export default {
  name: 'Role',
  components: {
    SetPermission
  },
  data() {
    return {
      loading: false,
      showDialog: false,
      tableData: [],
      roleForm: {
        name: '',
        description: '',
        state: 0
      },
      total: 0,
      pager: {
        page: 1,
        pagesize: 5
      },
      rules: {
        name: [
          { required: true, message: '请输入角色名称', trigger: 'blur' },
          { min: 2, max: 10, message: '角色名称应该为2-10个字符', trigger: 'blur' }
        ],
        description: [
          { required: true, message: '请输入角色描述', trigger: 'blur' },
          { min: 2, max: 10, message: '角色描述应该为1-100个字符', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.getRolesList()
  },
  methods: {
    // 获取表格信息
    async getRolesList() {
      this.loading = true
      const data = await getRolesList(this.pager)
      this.tableData = data.rows
      this.tableData.forEach(item => {
        /*
         *为每一条数据添加一个响应式数据isEdit
         *用来切换每一行的是否为编辑状态
         */
        this.$set(item, 'isEdit', false)
        /*
         *为每一条数据添加一个用于编辑的对象editRow
         *并在页面上使用该数据进行提交更新
         */
        this.$set(item, 'editRow', {
          name: item.name,
          description: item.description,
          state: item.state
        })
      })
      this.total = data.total
      this.loading = false
    },
    // 添加角色
    addRole() {
      this.$refs.form.validate(async(valid) => {
        if (valid) {
          await addRole(this.roleForm)
          await this.getRolesList()
          this.close()
          this.$message.success('添加成功')
        }
      })
    },
    // 分配权限
    handlePermission(id) {
      this.$refs.setPermission.open(id)
    },
    // 点击编辑按钮
    handleEdit(row) {
      row.isEdit = true
      // 重新获取数据,避免上次在表单中的数据残留
      row.editRow = {
        name: row.name,
        state: row.state,
        description: row.description
      }
    },
    // 更新数据
    async editRole(row) {
      if (row.editRow.name && row.editRow.description) {
        await editRole({
          ...row.editRow,
          id: row.id
        })
        // 在表格中显示更新后的数据
        Object.assign(row, {
          ...row.editRow,
          isEdit: false
        })
        this.$message.success('角色更新成功')
      } else {
        this.$message.error('角色名和描述不能为空')
      }
    },
    // 删除角色
    async handleDel(id) {
      await delRole(id)
      this.$message.success('删除成功')
      if (this.tableData.length === 1) {
        this.pagePrev()
      } else {
        await this.getRolesList()
      }
    },
    // 页面跳转
    pageChange(page) {
      this.pager.page = page
      this.getRolesList()
    },
    // 页面跳转
    pagePrev() {
      this.pager.page--
      this.getRolesList()
    },
    // 页面跳转
    pageNext() {
      this.pager.page++
      this.getRolesList()
    },
    // 关闭弹窗
    close() {
      this.showDialog = false
      this.$refs.form.resetFields()
    }
  }
}
</script>
<style scoped>
.role-operator{
  padding: 10px;
}
.pagination{
  padding: 20px;
  display:flex;
  justify-content: center;
  align-items: center;
}
</style>
